package demo.annotation.Test;

import demo.annotation.CourseInfoAnnotation;
import demo.annotation.PersonInfoAnnotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author: yu.zhou
 * @DateTime: 2023/01/03 17:21
 */
public class AnnotationParser {

    /**
     * 解析类型的方法
     *
     * @throws ClassNotFoundException
     */
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.Test.Course");
        // 获取当前类的注解而不是方法成员类的注解
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            CourseInfoAnnotation courseInfo = (CourseInfoAnnotation) annotation;
            System.out.println("课程名: " + courseInfo.courseName());
        }
    }

    public static void parseFieldAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.Test.Course");
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            // 判断成员变量中是否由指定注解类型的注解
            boolean isAnnotation = field.isAnnotationPresent(PersonInfoAnnotation.class);
            if (isAnnotation) {
                PersonInfoAnnotation personInfoAnnotation = field.getAnnotation(PersonInfoAnnotation.class);
                System.out.println("personName: " + personInfoAnnotation.name());
            }
        }
    }

    public static void parseMethodAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.Test.Course");
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            boolean annotationPresent = declaredMethod.isAnnotationPresent(CourseInfoAnnotation.class);
            if (annotationPresent) {
                CourseInfoAnnotation annotation = declaredMethod.getAnnotation(CourseInfoAnnotation.class);
                System.out.println("课程标签: " + annotation.courseTag());
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        parseTypeAnnotation();
        parseMethodAnnotation();
        parseFieldAnnotation();
    }
}
